import jsonwebtoken from 'jsonwebtoken';
import jwtConfig from '../config/jwtConfig';

export interface UserPamas{
  username:string;
  name?:string;
  avatar?:string;
  gender?:number; // 0 1 2
  phone?:number;
  accessToken?:string;
}

export default class JwtAuth{
  // 公共方法 静态方法 属于类 JwtAuth.signUserToken
  // userData(username, password ,nickname)
  public static signUserToken(userData:UserPamas,options?:any){
    try{
      return jsonwebtoken.sign(userData,jwtConfig.jwtSecret,options);
    }catch(err){
      console.log(err);
    }
  }

  public static verifyUserToken(token:string):any{
    try{
      console.log(token);
      const authorization  = token&& token.split(' ')[1];
      console.log(authorization);
      return jsonwebtoken.verify(authorization,jwtConfig.jwtSecret);
    }catch(err){
      throw {code :401,message:'no authorization'};
    }
  }

}

// const token = JwtAuth.signUserToken({username:'heihei'});
// console.log(token); // 签名eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImhlaWhlaSIsImlhdCI6MTY0NDk5MjU0Nn0.FWHpJ1fO6OdSBzUMMLQNQ3JoT0Zu_kSI7zKVcWowVz8
// const verifyRes = JwtAuth.verifyUserToken('yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImhlaWhlaSIsImlhdCI6MTY0NDk5MjU0Nn0.FWHpJ1fO6OdSBzUMMLQNQ3JoT0Zu_kSI7zKVcWowVz8');
// console.log(verifyRes); // 签名eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImhlaWhlaSIsImlhdCI6MTY0NDk5MjU0Nn0.FWHpJ1fO6OdSBzUMMLQNQ3JoT0Zu_kSI7zKVcWowVz8
//{ username: 'heihei', iat: 1644992546 } 验证成功
// { code: 401, message: 'no authorization' } 验证失败
